<template>
  <div>
    <!-- 摄像机 -->
    <canvas ref="videoCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  StartCameraCapture,
  StopCameraCapture,
} from "../../../../../wailsjs/go/api/CameraApi.js";

onMounted(async () => {
  await StartCameraCapture(); //直接开始
});

const videoCanvas = ref(null);
const img = new Image();
const ws1 = ref(null);
const ws2 = ref(null);
const cid1 = ref("");
const cid2 = ref("");

const startCamera = async (id) => {
  // 调用后端方法启动摄像头
  if (id === 1) {
    if (cid1.value !== "") {
      console.log("camera is already started");
      return;
    }
    ws1.value = new WebSocket("ws://localhost:8080/ws");
    ws1.value.onmessage = handleMessage; // 接收消息
    // ws1.value.onerror = handleOnError
  } else if (id === 2) {
    if (cid2.value !== "") {
      console.log("camera is already started");
      return;
    }
    ws2.value = new WebSocket("ws://localhost:8080/ws");
    ws2.value.onmessage = handleMessage2; // 接收消息
    // ws2.value.onerror = handleOnError
  }
};

const stopCamera = async (id) => {
  console.log(id);

  // 调用后端方法停止摄像头
  if (id === 1) {
    if (cid1.value === "") return;
    await StopCameraCapture(cid1.value); //停止摄像头
    if (ws1.value && ws1.value.readyState === WebSocket.OPEN) {
      ws1.value.close();
    }
    cid1.value = "";
    ws1.value = null;
  } else if (id === 2) {
    if (cid2.value === "") return;
    await StopCameraCapture(cid2.value); //停止摄像头
    if (ws2.value && ws2.value.readyState === WebSocket.OPEN) {
      ws2.value.close();
    }
    cid2.value = "";
    ws2.value = null;
  }
};

const handleMessage = (event) => {
//   console.log("websocket receive data", event.data);
  if (typeof event.data === "string") {
    const header = JSON.parse(event.data);
    if (header.type === "ping") {
      cid1.value = header.cid;
      console.log("cid is", header.cid);
    } else if (header.type === "data") {
      ws1.value.binaryType = "arraybuffer"; //下一个消息是二进制视频数据
    }
  } else if (event.data instanceof ArrayBuffer) {
    // 将ArrayBuffer转为Blob
    const blob = new Blob([event.data], { type: "image/jpeg" });
    const url = URL.createObjectURL(blob);
    // 渲染到Canvas
    img.onload = () => {
      const ctx = videoCanvas.value.getContext("2d");
      ctx.drawImage(
        img,
        0,
        0,
        videoCanvas.value.width,
        videoCanvas.value.height
      );
      URL.revokeObjectURL(url); // 释放内存
    };
    img.src = url;
  }
};

const handleMessage2 = (event) => {
  const value = JSON.parse(event.data);
  if (value.type === "ping") {
    cid2.value = value.cid;
    console.log("cid is", value.cid);
  } else if (value.type === "data") {
    cameraImg2.value = value.data;
  }
};

defineExpose({
  startCamera,
  stopCamera,
});
</script>

<style scoped lang="scss">
</style>